package com.example.graduationdesignbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.graduationdesignbackend.constants.ResponseCode;
import com.example.graduationdesignbackend.dto.PageDto;
import com.example.graduationdesignbackend.entity.News;
import com.example.graduationdesignbackend.exception.ParkException;
import com.example.graduationdesignbackend.mapper.NewsMapper;
import com.example.graduationdesignbackend.query.NewsQuery;
import com.example.graduationdesignbackend.res.Res;
import com.example.graduationdesignbackend.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuze
 * @since 2024-04-03
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {

  @Override
  public void createNews(News news) {
    News news1 = news;
    news1.setId(RandomUtil.randomNumbers(9));
    news1.setStatus(0);
    news1.setCreateTime(new Date().getTime());
    news1.setUpdateTime(new Date().getTime());
    Boolean save = save(news1);
    if (!save) throw new ParkException(ResponseCode.SaveError);
  }

  @Override
  public Res editNews(News news) {
    News news1 = BeanUtil.toBean(news,News.class);
    news1.setUpdateTime(new Date().getTime());
    Boolean update = updateById(news1);
    if (!update) throw new ParkException(ResponseCode.UpdateError);
    return Res.yuze();
  }

  @Override
  public PageDto<News> getNewsPages(NewsQuery newsQuery) {
    String key = newsQuery.getKey();
//    构建查询条件
    String type = newsQuery.getType();
    String status = newsQuery.getStatus();
//    构建分页条件
    int current = 1;
    if (!BeanUtil.isEmpty(newsQuery.getCurrent())){
      current = newsQuery.getCurrent();
    }
    int pageSize = 10;
    if (!BeanUtil.isEmpty(newsQuery.getPageSize())){
      pageSize = newsQuery.getPageSize();
    }
    Page<News> page = Page.of(current,pageSize);
    page.addOrder(new OrderItem("online_time",false));
    Page<News> p = new Page<>();
    if (BeanUtil.isEmpty(newsQuery.getKey())){
      p = lambdaQuery()
              .eq(News::getTypeCode,type)
              .page(page);
    }else {
      p = lambdaQuery()
              .eq(News::getTypeCode,type)
              .like(News::getTitle,key)
              .page(page);
    }
//    分页查询
    PageDto<News> dto = new PageDto<>();
    dto.setTotal(p.getTotal());
    dto.setPages(p.getPages());
    dto.setPageSize(p.getSize());
    dto.setCurrent(p.getCurrent());
    dto.setList(p.getRecords());
    return dto;
  }
}
